package com.yisu.kabao.manager.core.service.impl;

import com.yisu.kabao.ewf.entity.GoodsInfo;
import com.yisu.kabao.ewf.entity.Prize;
import com.yisu.kabao.manager.core.mapper.GoodsInfoMapper;
import com.yisu.kabao.manager.core.mapper.PrizeMapper;
import com.yisu.kabao.manager.core.service.IPrizeService;
import com.yisu.kabao.manager.core.service.impl.func.LuckyNumberUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * author: 赵杰
 * Business Description：奖品类相关业务实现
 * createTime：2017/8/10
 */
@Service("IPrizeService")
public class PrizeServiceImpl extends BaseService implements IPrizeService {
    @Resource
    private PrizeMapper prizeMapper;
    @Resource
    private GoodsInfoMapper goodsInfoMapper;

    /**
     * author:赵杰
     * Business Description : 通过商品ID，开始进行夺宝操作
     *
     * @param goodsId 商品ID
     * @return
     */
    @Override
    public boolean startSnatchTreasure(long goodsId) {
        try {
            GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(goodsId);
            if (goodsInfo == null || (goodsInfo != null && goodsInfo.getStatus() == GoodsInfo.StatusEnum.SNATCH_TREASURE_ING.code))
                return false;
            //获取最大期号
            Integer maxTerm = goodsInfoMapper.getMaxTermByGoodsId(goodsId) + 1;
            //生成幸运号，成功则开启新一期夺宝
            if (LuckyNumberUtil.createLuckyNumberByGoodsId(goodsInfo.getId(), goodsInfo.getPrice(), maxTerm)) {
                GoodsInfo updateGoodsInfo = new GoodsInfo();
                updateGoodsInfo.setId(goodsId);
                updateGoodsInfo.setTerm(maxTerm);
                updateGoodsInfo.setStatus(GoodsInfo.StatusEnum.SNATCH_TREASURE_ING.code);
                goodsInfoMapper.updateByPrimaryKeySelective(updateGoodsInfo);
                Prize insertPrize = new Prize();
                insertPrize.setCreateDate(new Date());
                insertPrize.setIsValid(true);
                insertPrize.setGoodsId(goodsId);
                insertPrize.setStartTime(new Date());
                insertPrize.setPartakeNum(0);
                insertPrize.setPrice(goodsInfo.getPrice());
                insertPrize.setName(goodsInfo.getName());
                insertPrize.setGoodsTypeId(goodsInfo.getGoodsTypeId());
                insertPrize.setTerm(maxTerm);
                insertPrize.setImage(goodsInfo.getImages());
                insertPrize.setStatus((byte) Prize.StatusTypeEnum.SNATCH_TREASURE_ING.code);
                insertPrize.setIsTen(goodsInfo.getIsTen());
                insertPrize.setIsRechargeableCard(goodsInfo.getIsRechargeableCard());
                insertPrize.setGoodsDetail(goodsInfo.getDetail());
                prizeMapper.insertSelective(insertPrize);
                return true;
            }
            return false;
        } catch (Exception e) {
            logger.error("通过商品ID，开始进行夺宝操作异常：" + e.getMessage());
        }
        return false;
    }
}
